package neo.core.common;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

public abstract class BaseCache extends GeneralCacheAdministrator {
	protected static final Log log = LogFactory.getLog(BaseCache.class);
	private String preKey;

	/*
	 * 获取真实数据（往往来自数据库－通过调用Service方法）
	 */
	public abstract Object getRealValue(String myKey);

	public BaseCache() {
		this("");
	}

	public BaseCache(String preKey) {
		super(getDefaultProp());
		this.preKey = preKey;
	}

	/**
	 * 这里可添加默认参数对BaseCache进行配置
	 * @return 参数值
	 */
	public static Properties getDefaultProp() {
		Properties p = new Properties();
		/*
		//可设置初始参数
		p.setProperty("cache.event.listeners",
				"com.opensymphony.oscache.plugins.clustersupport.JavaGroupsBroadcastingListener");
		*/
		return p;
	}

	/*
	 * 如果使用Group，需要Override此方法
	 */
	public String[] getGroups(String myKey) {
		return null;
	}

	/*
	 * 获得缓存的数据
	 */
	public Object getCachedValue(String myKey, int refreshPeriod) {
		String cacheKey = preKey + myKey;
		boolean updated = false;
		Object myValue = null;
		try {
			// Get from the cache
			myValue = getFromCache(cacheKey, refreshPeriod);
		} catch (NeedsRefreshException nre) {
			try {
				// Get the value (probably by calling an Service)
				myValue = getRealValue(myKey);
				// Store in the cache
				putInCache(cacheKey, myValue, getGroups(myKey));
				updated = true;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (!updated) {
					// It is essential that cancelUpdate is called if the
					// cached content could not be rebuilt
					cancelUpdate(cacheKey);
				}
			}
		}
		return myValue;
	}

	public void flushEntry(String myKey) {
		super.flushEntry(preKey + myKey);
	}
}